package com.wquick.base.utils

import android.graphics.Rect
import android.view.ViewTreeObserver
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalView

/**
 *  val isKeyboardOpen by KeyboardAsState() // Keyboard.Opened or Keyboard.Closed
 *
 * Keyboard helper
 *
 * @constructor Create empty Keyboard helper
 */
object KeyboardHelper {

    enum class Keyboard {
        Opened, Closed
    }

    @Composable
    fun KeyboardAsState(): State<Keyboard> {
        val keyboardState = remember { mutableStateOf(Keyboard.Closed) }
        val view = LocalView.current
        DisposableEffect(view) {
            val onGlobalListener = ViewTreeObserver.OnGlobalLayoutListener {
                val rect = Rect()
                view.getWindowVisibleDisplayFrame(rect)
                val screenHeight = view.rootView.height
                val keypadHeight = screenHeight - rect.bottom
                keyboardState.value = if (keypadHeight > screenHeight * 0.15) {
                    Keyboard.Opened
                } else {
                    Keyboard.Closed
                }
            }
            view.viewTreeObserver.addOnGlobalLayoutListener(onGlobalListener)

            onDispose {
                view.viewTreeObserver.removeOnGlobalLayoutListener(onGlobalListener)
            }
        }

        return keyboardState
    }
}